<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChContactMapper;
use App\CustHub\Mapper\ChCorpMapper;
use App\CustHub\Mapper\ChListenContactMapper;
use App\CustHub\Mapper\ChListenRoomBehaviorMapper;
use App\CustHub\Mapper\ChListenRoomLogMapper;
use App\CustHub\Mapper\ChListenRoomMapper;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Mapper\ChRoomMapper;
use App\CustHub\Mapper\ChRoomMemberMapper;
use App\CustHub\Model\ChCorp;
use App\CustHub\Model\ChListenContactRoom;
use App\CustHub\Model\ChListenRoomBehavior;
use App\Robot\Service\RobotApiService;
use FriendsOfHyperf\Lock\Exception\LockTimeoutException;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Exception\NormalStatusException;
use Mine\MineModel;
use function FriendsOfHyperf\Lock\lock;
use function Hyperf\Support\optional;

class ChListenContactService extends AbstractService
{
    public $mapper;

    #[Inject]
    public  ChContactMapper $contactMapper;

    #[Inject]
    public  ChListenRoomBehaviorMapper $chListenRoomBehaviorMapper;

    #[Inject]
    public  ChRoomMemberMapper $chRoomMemberMapper;

    #[Inject]
    public  ChRobotMapper $robotMapper;

    #[Inject]
    public  ChListenRoomLogMapper $roomListenLogMapper;

    #[Inject]
    protected ChConfigService $configService;

    #[Inject]
    public  ChRoomMapper $roomMapper;

    public function __construct(ChListenContactMapper $mapper)
    {
        $this->mapper = $mapper;
    }


    public function getListenContactByDay($params)
    {
        $contactBuild = $this->chListenRoomBehaviorMapper->model::query()->where('main_uid',$params['main_uid'])->where('room_id',$params['room_id']);
        $paginate=$contactBuild->selectRaw(
            "DATE_FORMAT(created_at, '%Y-%m-%d') as date,
            COUNT(CASE WHEN behavior_type = 1 THEN 1 END) as in_room_total,
            COUNT(CASE WHEN behavior_type = 2 THEN 1 END) as out_room_total,
            SUM(CASE WHEN behavior_type = 3 then times else 0 end) as speek_total,
            COUNT(DISTINCT CASE WHEN  behavior_type = 3 then user_id else null end) as speek_people_total"
        )   ->groupBy("date")
            ->orderBy("date",'desc')
            ->paginate((int)$params['page_size']);
        $paginate->getCollection()->transform(function ($item) {
            $member_total=$this->chRoomMemberMapper->model::query()->where('room_wxid',$item['room_wxid'])->where(function ($query) use ($item) {
                // 要么没有退群时间，要么退群时间晚于统计日期
                $query->whereNull('out_time')
                    ->orWhere('out_time', '>', $item->date . ' 23:59:59');
            })
            ->count();
            $item->member_total=$member_total;
            $item->liveness=$member_total>0?bcdiv((string)($item->speek_people_total*100),(string)$member_total,2):0;
            return $item;
        });
        return $this->roomMapper->setPaginate($paginate);
    }

    public function getListenContactList($params)
    {
        $pageSize = $params['page_size'] ?? MineModel::PAGE_SIZE;

        $list = $this->mapper->model::query()->with(['user'=>function ($query) {
            $query->select('id','nickname');
        },'robot'=>function ($query) {
            $query->select('id','nickname','avatar','corp_name');
        }])->leftJoin('ch_listen_room_behavior','ch_listen_room_behavior.robot_id','=','ch_listen_contact.robot_id')
            ->selectRaw("ch_listen_contact.*,
               count(1) as listen_room_total,
               SUM(CASE WHEN  ch_listen_room_behavior.behavior_type = 3 then ch_listen_room_behavior.times else 0 end) as speek_total")
            ->where('ch_listen_contact.main_uid',$params['main_uid'])
            ->paginate((int)$pageSize);
        $list->getCollection()->transform(function ($item) {
            $item->average_rate=0;
            $item->average_speek_total=0;
            return $item;
        });
        return $this->mapper->setPaginate($list);
    }


    public function getConfig($params)
    {
        return $this->configService->getConfigByGroupKey($params['uid'],$params['main_uid'],'listen_room');
    }

    public function deleteListen($params)
    {
        $ids = explode(",",$params['ids']);
        $result = $this->mapper->delete($ids);
        return $result;
    }

    public function addListenContact($params)
    {
        $robots=explode(',',$params['robot_ids']);
        foreach ($robots as $robot_id){
            $listenRoom=$this->mapper->getModel()->query()->where([
                'main_uid'=>$params['main_uid'],
                'uid'=>$params['uid'],
                'robot_id'=>$robot_id,
            ])->first();
            if (empty($listenRoom)){
                $listenRoom=$this->mapper->getModel()->query()->create([
                    'main_uid'=>$params['main_uid'],
                    'uid'=>$params['uid'],
                    'robot_id'=>$robot_id,
                ]);
            }
        }
        if(!empty($params['room_ids'])){
            $params['listen_contact_id']=$listenRoom->id;
            container()->get(ChListenContactRoomService::class)->addListenContact($params);
        }
        return true;
    }

}